//
//  XMGWebViewController.m
//  BuDeJie
//
//  Created by 陈恒均 on 2018/1/25.
//  Copyright © 2018年 小码哥. All rights reserved.
//

#import "XMGWebViewController.h"
#import <WebKit/WebKit.h>

@interface XMGWebViewController ()
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (nonatomic, weak) WKWebView *webView;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *goBack;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *goFoward;
@end

@implementation XMGWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WKWebView *webView = [[WKWebView alloc] init];
    self.webView = webView;
    [self.contentView addSubview:webView];
    
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:_url];
    [webView loadRequest:request];
    

    [webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    self.goBack.enabled =self.webView.canGoBack;
    self.goFoward.enabled =self.webView.canGoForward;
    self.title = self.webView.title;
    self.progressView.progress = self.webView.estimatedProgress;
    self.progressView.hidden = self.webView.estimatedProgress >= 1;
    
}
- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"canGoBack"];
    [self.webView removeObserver:self forKeyPath:@"canGoForward"];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];

}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    self.webView.frame = self.contentView.bounds;
    
}

- (IBAction)reload:(UIBarButtonItem *)sender {
    [self.webView reload];
}
- (IBAction)goFoward:(id)sender {
    [self.webView goForward];
}
- (IBAction)goBack:(id)sender {
    [self.webView goBack];
}




@end
